<?php
namespace app\common\lib\module_config\tagsconfig;

use app\common\lib\model_operate\QueryDevice;
use app\common\lib\model_operate\Tools;
use app\common\lib\module_config\FormCtrl;
use app\common\lib\module_config\TagsConfig;
use app\common\lib\module_config\FormSee;
use think\Db;

class Detail extends TagsConfig
{
    private $where; // 根据search 参数规则生成的查询条件

    private $base; //主表信息

    /**
     * 构造
     */
    public function __construct($trace, $tags)
    {
        parent::__construct($trace, $tags);

        //设置主表信息
        $this->setBase();

    }

    /**
     * 设置主表信息
     */
    private function setBase()
    {
        if(empty($this->config['database'])){
            //主表名
            $this->base['tableName'] = Tools::tableNameFormat($this->trace->getApp(), 1);
        }else{
            //主表名
            $this->base['tableName'] = Tools::tableNameFormat($this->config['database'], 1);
        }

        //获取主表字段
        $this->base['tableInfo']     = DB::getTableInfo($this->base['tableName']);
        $this->base['displayFields'] = [];

    }

    /**
     * 获取主表信息
     */
    public function getBase()
    {
        return $this->base;
    }

    /**
     * 获取搜索参数的条件
     */
    public function getWhere()
    {
        return $this->where;
    }

    /**
     * 设置动态参数
     */
    public function setParam(array $param = [])
    {
        return true;
    }

    public function createHtml($list = [])
    {
        // $fo = new FormCtrl($this->trace,$this->tags);
        $fo = new FormSee($this->trace,$this->tags);

        $fo->setList($list);

        $html = '';

        if (empty($this->config['fields'])) {
            return '';
        }

        $this->transformshow($list);

        foreach ($this->config['fields'] as $key => $value) {

            // if (!in_array($value['field'], array_keys($list))) {
            //     continue;
            // }
            if(!empty($value['permission']) && $value['permission'] == '1'){
                //检查权限
                $check = ( new \plugins\store\Common )->getAllowAccess();
                if($check === true){
                }else{
                    continue;
                }
            }
            if ($value['show_type'] == 1) {
                $value['option'] = $this->selectGetTableData($value['option']);
            } elseif ($value['show_type'] == 2) {
                $value['option'] = json_decode($value['option'], true);
            } elseif ($value['show_type'] == 3) {
                $value['option'] = json_decode($value['option'], true);
            }

            // $value['default'] = $list[$value['field']];
            $value['default'] = (!in_array($value['field'], array_keys($list))) ? '' : $list[$value['field']];

            if ($value['is_show'] == 1) {
                $html .= $fo->setHtml($value);
            }
            //  else {
            //     $html .= $fo->setHidden( $value );
            // }
        }
        return $html;
    }

    //生成一个表格
    //$num每行数据量
    public function createTableHtml($list = [],$num = 2)
    {
        $fo = new FormSee($this->trace,$this->tags);

        $fo->setList($list);

        $html = '';

        if (empty($this->config['fields'])) {
            return '';
        }

        //数据处理
        $this->transformshow($list);

        //$i换行计数
        $i = 1;

        $width_th = 100/$num/3;
        $width_td = $width_th * 2;
        $html .= "<table class='layui-table layui-nomargin'>";
        //遍历配置
        foreach ($this->config['fields'] as $key => &$value) {
            //是否显示检测
            if ($value['is_show'] != 1) {
                continue;
            }
      
            //permission权限检测
            if(!empty($value['permission']) && $value['permission'] == '1'){
                //检查权限
                $check = ( new \plugins\store\Common )->getAllowAccess();
                if($check === true){

                }else{
                    continue;
                }
            }
            if($i == 1 ){
                $html .= "<t>";
            }
            $html .= "<td width='".$width_th."%' align='right'><b>".$value['title']."</b></td>";

            //原样输出
            if ($value['show_type'] == 0) {
                if($value['ctrl_type'] == 'oneimage'){
                    $img = '<img src="__ROOT__'.$list[$key].'" class="layui-upload-img" id="img-'.$value['field'].'" style="width:92px;height:92px;margin:0 10px 10px 0;">';
                    $html .="<td width='".$width_td."%'>".$img."</td>";
                }elseif( $value['ctrl_type'] == 'moreimage'){
                    $moreimage = json_decode($list[$key]);
                    $img ='';
                    foreach( $moreimage as $k => $va ){
                    $img .= '<img src="__ROOT__'.$va.'" class="layui-upload-img" id="img-'.$value['field'].'" style="width:92px;height:92px;margin:0 10px 10px 0;">';
                    }
                    $html .="<td width='".$width_td."%'>".$img."</td>";
                }else{
                $html .= "<td width='".$width_td."%'>".$list[$key]."</td>";
                }

            }elseif($value['show_type'] == 1){

            //固定内容
            } elseif ($value['show_type'] == 2) {
                //获取配置
                $option = json_decode($value['option'], true);
                $html .= "<td width='".$width_td."%'>".$option[$list[$key]]."</td>";
            //多选项
            } elseif ($value['show_type'] == 3) {
                //获取配置
                $option = json_decode($value['option'], true);
            }

            if($i == $num){
                $html .= "</tr>";
                $i = 1;
            }else{
                $i ++ ;
            }

        }
        if($i != 1){
            for ($s = 0; $s < ($num-$i+1); $s++) { 
                $html .= "<th></th><td></td>";
            }
            $html .= "</tr>";
        }
        $html .= "</table>";
        return $html;        
    }

    /**
     * 数据处理
     */
    public function transformshow(&$list)
    {

        $config = $this->config['fields'];

        unset($list['_plugin'], $list['_controller'], $list['_action']);

        foreach ($list as $key => $value) {

            if (empty($config[$key])) {
                continue;
            }

            switch ($config[$key]['ctrl_type']) {
                case 'date':
                    if(!empty($list[$key])){
                        $list[$key] = date('Y-m-d H:i:s', $list[$key]);
                    }
                    break;
                case 'checkbox':
                    $list[$key] = json_decode($list[$key], true);
                    break;
                case 'radio':

                    break;
                case 'ueditor':
                    $list[$key] = autoHtmlspecialcharsDecode($list[$key]);
                break;
                default:
                    # code...
                    break;
            }
        }

        return $list;
    }

    /**
     * 查表显示数据
     */
    private function selectGetTableData($option)
    {
        $da     = [];
        $option = json_decode($option, true);
        if (!empty($option) && count($option) == 3) {
            list($table, $fields, $items) = $option;
            $table                        = Tools::tableNameFormat($table);
            $tb                           = Db::name($table)->field($fields)->select()->toArray();
            foreach ($items as $key => $value) {
                if (false === strpos($key, '$') && false === strpos($value, '$')) {
                    $da[$key] = $value;
                } else {
                    $ik = str_replace("$", '', $key);
                    $iv = str_replace("$", '', $value);
                    $a  = array_column($tb, $iv, $ik);
                    $da = $da + $a;
                }
            }
        }
        return $da;
    }

    /**
     * 执行查询
     */
    public function query()
    {
        $type = (isset($this->relevance['relevanceType']['queryType']) && !empty($this->relevance['relevanceType']['queryType'])) ? $this->relevance['relevanceType']['queryType'] : 'Single';
        return QueryDevice::createQuery($this, $type);
    }

}
